package view;

import java.awt.Dimension;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Queue;

import javax.swing.JLayeredPane;
import javax.swing.JPanel;

import model.Container;
import model.Player;
import model.Preference;
import util.IView;
import util.PlayerUtilities;

public class PageLayout extends JLayeredPane implements IView {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1709101212209086483L;

	private Player player;


	private Queue<ContainerView> containerViews;

	public PageLayout(Player player) {
		this.player = player;
		this.player.addView(this);
		Preference.getInstance().addView(this);
		this.containerViews = new LinkedList<ContainerView>();

		this.setLayout(null);
		this.setupBoxes();

		// add a download progress bar at the bottom
		double scale = Preference.getInstance().getScale();
		setupDownloadBar(scale);
	}
	
	private void setupDownloadBar(double scale) {
		DownloadProgressBar downloadBar = new DownloadProgressBar();
		int downloadBarHeight = 30;
		downloadBar.setBounds(0, PlayerUtilities.scale(Preference.getInstance().getPlayerHeight(), scale) - downloadBarHeight, PlayerUtilities.scale(
				Preference.getInstance().getPlayerWidth(), scale), downloadBarHeight);
		this.add(downloadBar);
		this.setLayer(downloadBar, JLayeredPane.POPUP_LAYER);
		downloadBar.setVisible(false);
	}

	private void setupBoxes() {
		// scale of the containers
		double scale = Preference.getInstance().getScale();
		this.setPreferredSize(new Dimension(PlayerUtilities.scale(Preference.getInstance().getPlayerWidth(), scale), PlayerUtilities.scale(Preference
				.getInstance().getPlayerHeight(), scale)));

		Collection<Container> containers = this.player.getContainers();

		// prevent concurrent access to this list
		synchronized (containers) {
			for (Container c : containers) {
				ContainerView cView = new ContainerView(c, scale);
				this.containerViews.add(cView);
				this.add(cView);
				this.setLayer(cView, cView.getDepth());
			}
		}
		JPanel cover = new JPanel();
		this.setLayer(cover, JLayeredPane.DRAG_LAYER);
		this.add(cover);
		this.invalidate();
		this.revalidate();
		this.repaint();
	}

	@Override
	public void updateView(Object obj, Object additionalInformation) {
		this.removeContainers();
		this.setupDownloadBar(Preference.getInstance().getScale());
		this.setupBoxes();
	}

	private void removeContainers() {
		while (!this.containerViews.isEmpty()) {
			ContainerView v = this.containerViews.poll();
			// System.out.println(Thread.currentThread().getName());
			v.cleanup();
		}
		this.removeAll();
	}

}
